/**
 * 安全日志配置模块
 * EndoSight-UC 医疗AI系统 - 焦土协议安全修复
 * 
 * 确保敏感信息不会被记录到日志文件中
 */

import winston from 'winston';

// 敏感信息过滤器
const sensitiveDataFilter = winston.format((info) => {
  const sensitiveKeys = [
    'password', 'token', 'secret', 'key', 'authorization',
    'JWT_SECRET', 'DEEPSEEK_API_KEY', 'DB_PASSWORD'
  ];
  
  const sensitivePatterns = [
    /sk-[a-zA-Z0-9]+/g, // API keys
    /Bearer\s+[A-Za-z0-9\-._~+\/]+=*/g, // JWT tokens
    /password["\s:]+["']?[^"'\s,}]+["']?/gi, // passwords
    /using password:\s+YES/gi // MySQL password logs
  ];

  // 递归清理对象中的敏感信息
  const cleanObject = (obj) => {
    if (typeof obj !== 'object' || obj === null) {
      return obj;
    }

    const cleaned = {};
    for (const [key, value] of Object.entries(obj)) {
      const lowerKey = key.toLowerCase();
      
      // 检查是否为敏感键名
      if (sensitiveKeys.some(sensitive => lowerKey.includes(sensitive))) {
        cleaned[key] = '[REDACTED]';
        continue;
      }

      // 递归清理嵌套对象
      if (typeof value === 'object' && value !== null) {
        cleaned[key] = cleanObject(value);
      } else if (typeof value === 'string') {
        // 清理字符串中的敏感信息
        let cleanedValue = value;
        for (const pattern of sensitivePatterns) {
          cleanedValue = cleanedValue.replace(pattern, '[REDACTED]');
        }
        cleaned[key] = cleanedValue;
      } else {
        cleaned[key] = value;
      }
    }
    
    return cleaned;
  };

  // 清理日志信息
  return cleanObject(info);
});

// 安全日志格式
const secureFormat = winston.format.combine(
  sensitiveDataFilter(),
  winston.format.timestamp(),
  winston.format.errors({ stack: true }),
  winston.format.json()
);

// 控制台格式（开发环境）
const consoleFormat = winston.format.combine(
  sensitiveDataFilter(),
  winston.format.colorize(),
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
  winston.format.printf(({ level, message, timestamp, ...meta }) => {
    let msg = `${timestamp} [${level}]: ${message}`;
    
    // 添加元数据（但不包含敏感信息）
    if (Object.keys(meta).length > 0) {
      msg += ` ${JSON.stringify(meta)}`;
    }
    
    return msg;
  })
);

// 创建安全日志记录器
export const createSecureLogger = (options = {}) => {
  const {
    service = 'endo_sight_uc',
    logLevel = process.env.LOG_LEVEL || 'info',
    logFile = 'logs/app.log'
  } = options;

  const transports = [
    new winston.transports.Console({
      format: process.env.NODE_ENV === 'production' ? secureFormat : consoleFormat,
      level: logLevel
    })
  ];

  // 生产环境添加文件日志
  if (process.env.NODE_ENV === 'production') {
    transports.push(
      new winston.transports.File({
        filename: logFile,
        format: secureFormat,
        level: logLevel,
        maxsize: 10485760, // 10MB
        maxFiles: 5
      })
    );
  }

  const logger = winston.createLogger({
    level: logLevel,
    format: secureFormat,
    defaultMeta: { service },
    transports
  });

  // 添加安全方法
  logger.logSecurityEvent = (eventType, details, severity = 'info') => {
    logger[severity](`SECURITY_EVENT: ${eventType}`, {
      eventType,
      timestamp: new Date().toISOString(),
      ...details
    });
  };

  logger.logError = (error, context = {}) => {
    logger.error('APPLICATION_ERROR', {
      message: error.message,
      stack: error.stack,
      ...context
    });
  };

  return logger;
};

export default {
  createSecureLogger,
  secureFormat,
  sensitiveDataFilter
};
